package tk.mybatis.springboot.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @author liran
 */
public class ThreadFactoryUtil {

    /**
     * 线程池
     */
    public static ExecutorService threadPool = new ThreadPoolExecutor(10, 100,
            2L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), new ThreadFactoryBuilder()
            .setNameFormat("send-msg-pool-%d").build(), new ThreadPoolExecutor.CallerRunsPolicy());


    /**
     * 线程池的核心线程会销毁吗？
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(4,10,5, TimeUnit.SECONDS,new LinkedBlockingDeque<>(20));
        //pool.allowCoreThreadTimeOut(true);
        int a = 10;

        for (int i = 1; i <= a; i++) {
            int j = i;
            pool.submit(() -> {
                if(j == 10){
                    throw new RuntimeException();
                }
                //获取线程名称
                Thread thread = Thread.currentThread();
                String name = thread.getName();
                //输出
                int activeCount = pool.getActiveCount();
                System.out.println("任务："+j+"-----,线程名称:"+name+"-----活跃线程数:"+activeCount+"-----线程数"+pool.getPoolSize());
            });
        }
        Thread.sleep(6000);
        System.out.println("线程数"+pool.getPoolSize()+"-----,活跃线程数"+pool.getActiveCount());
    }
}
